/**
 * Copyright (C), 2018 store
 * Encoding: UTF-8
 * Date: 19-12-11 上午10:03
 * History:
 */
package com.swak.frame.excel.adapter;

import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;

import com.swak.frame.excel.AbstractLoaderSupportFactory;
import com.swak.frame.excel.ExcelLoaderFactory;
import com.swak.frame.excel.csv.CsvLoaderFactory;


/**
 * LoaderSupportAdapter.java
 *
 * @author ColleyMa
 * @version 19-12-11 上午10:03
 */
public class LoaderSupportAdapter extends AbstractLoaderSupportFactory {
    private final static String[] EXCEL_EXTENSION = {"xls", "xlsx"};
    private final static String[] CSV_EXTENSION = {"csv"};

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
    }

    @Override
    public void loadProp(Map<String, Map<String, String>> localProp) {
        if (this.locations != null) {
            for (Resource location : this.locations) {
                String fileName = location.getFilename();
                String suffix = StringUtils.substringAfter(fileName, ".");

                if (ArrayUtils.contains(EXCEL_EXTENSION, suffix)) {
                    // excel
                    try {
                        ExcelLoaderFactory excelLoaderFactory = new ExcelLoaderFactory();
                        excelLoaderFactory.setFileEncoding(this.fileEncoding);
                        excelLoaderFactory.setLocation(location);
                        excelLoaderFactory.afterPropertiesSet();
                        localProp.putAll(excelLoaderFactory.getLocalProp());
                    } catch (Exception e) {
                        logger.error("loader excel prop error!", e);
                    }
                }

                if (ArrayUtils.contains(CSV_EXTENSION, suffix)) {
                    // csv
                    try {
                        CsvLoaderFactory cvsLoaderFactory = new CsvLoaderFactory();
                        cvsLoaderFactory.setFileEncoding(this.fileEncoding);
                        cvsLoaderFactory.setLocation(location);
                        cvsLoaderFactory.afterPropertiesSet();
                        localProp.putAll(cvsLoaderFactory.getLocalProp());
                    } catch (Exception e) {
                        logger.error("loader csv prop error!", e);
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        String fileName = "catelist.csv";
        String suffix = StringUtils.substringAfter(fileName, ".");
        System.err.println(suffix);
    }
}
